/*udp服务器*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>

#ifndef STR_CONV
#include "./libs/functions.h"
#endif

#ifndef ERRORS
#include "./errors.c"
#endif

const int PORT = 9506;

int main() {
    //TCP 参数： SOCK_STREAM、IPPROTO_TCP ；UDP参数： SOCK_DGRAM 、IPPTOTO_UDP
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        printf("%s\n", UDP_SOCK_INIT_FAIL);
        return -1;
    }

    struct sockaddr_in server_socket, client_socket;
    int sockopt = 0;
    sockopt = SO_REUSEADDR;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockfd, sizeof(sockfd));

    //对结构体变量内存初始化
    int server_socket_len = sizeof(server_socket);
    memset(&server_socket, 0, server_socket_len);

    server_socket.sin_family = AF_INET; //选择IPV4地址类型
    server_socket.sin_port = htons(PORT); //选择端口号
    server_socket.sin_addr.s_addr = inet_addr("0.0.0.0"); //选择IP地址

    if (bind(sockfd, (struct sockaddr *) &server_socket, server_socket_len) < 0)//绑定套接字
    {
        printf("%s\n", UDP_SOCK_BIND_FAIL);
        return -1;
    }
    // 定义数据缓冲区
    char buf[BUFSIZ] = {0};
    int recv_data_len = 0;
    char tmp_out_res[BUFSIZ] = {0};
    socklen_t client_socket_len = sizeof(client_socket);
    while (1)    //实现了循环监听
    {
        recv_data_len = recvfrom(sockfd, buf, BUFSIZ, 0, (struct sockaddr *) &client_socket, &client_socket_len);
        buf[BUFSIZ] = '\0';
        if (!is_utf8_format(buf)) {
            // 以下函数的最后一个参数，输出缓冲区的长度计算依据：在linux系统，gbk编码占2字节，utf8 编码占3字节，也就是说，你输入了一个中文字，那么输出空间的长度就是输入空间的1.5倍，保险起见，我们就直接设置为 2倍
            gbk_to_utf8(buf, recv_data_len, tmp_out_res, recv_data_len * 2);
            if (errno != 0) {
                printf("%s，错误编码：%d, 错误信息：%s\n", STRCONV_FAIL, errno, strerror(errno));
                continue;
            }
        }else{
            strcpy(tmp_out_res,buf);
        }
        tmp_out_res[BUFSIZ] = '\0';
        //获取客户端的基本信息，ip、port
        printf("Client_IP: %s\n", inet_ntoa(client_socket.sin_addr));
        printf("Client_Port: %d\n", htons(client_socket.sin_port));

        //通过 sockfd 向客户端回复消息
        int send_data_len = sendto(sockfd, tmp_out_res, strlen(tmp_out_res), 0, (struct sockaddr *) &client_socket, client_socket_len);
        printf("发送的数据长度：%d,是否成功：%s\n", send_data_len, strerror(errno));
        memset(buf, 0, BUFSIZ);
        memset(tmp_out_res, 0, BUFSIZ);
    }

    close(sockfd);
    return 0;
}
